from urllib import request
import urllib.error
import os, requests, sys, bz2, gzip
from lxml import html
import urllib.parse
import xml.dom.minidom
from globally import WorkPath




# 用于获取url中的repodata下primary文件里的软件包及其对应的sha256的值。
class PackSHA256:
    # 下载对应url中的repodata下的*。primary*的文件
    def _download_primaryfile(self, url):
        response = requests.get(url + "repodata/")
        if response.status_code == 200:
            result = []
            html_content = response.text
            tree = html.fromstring(html_content)
            links = tree.xpath('//a/@href')
            for mumber in links:
                if "primary.xml" in mumber:
                    result.append(mumber)
            if len(result) == 1:
                downloadurl = url + "repodata/" + result[0]
                destpath = WorkPath + result[0]
                opener = urllib.request.build_opener()
                opener.addheaders = [('User-Agent',
                                      'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
                urllib.request.install_opener(opener)
                urllib.request.urlretrieve(downloadurl, destpath)
                return destpath
            elif  "https://update.cs2c.com.cn/NS/V10/V10SP3-2403/os/adv/lic/base/x86_64/" in url and len(result) == 2:
            # 针对v10sp3-2403 x86架构，在repodata里存在两个primary.xml文件，经过分析该问题为研发配置问题。所以在此单独处理。其他版本尚未发现该问题
                downloadurl = url + "repodata/" + result[1]
                destpath = WorkPath + result[1]
                opener = urllib.request.build_opener()
                opener.addheaders = [('User-Agent',
                                      'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
                urllib.request.install_opener(opener)
                urllib.request.urlretrieve(downloadurl, destpath)
                return destpath
            else:
                print("寻找sha256文件失败")
                sys.exit(0)

    # 读取primary文件中的信息。生成{包名：sha256值}的键值对
    def _read_primaryfile(self, primaryfile):
        if primaryfile.endswith("bz2"):
            f = bz2.open(primaryfile, "rb", encoding='utf-8')
        elif primaryfile.endswith("gz"):
            f = gzip.open(primaryfile, 'rt', encoding='utf-8')
        else:
            print("sha256文件既不属于 bz2 ，也不属于 gz")
            sys.exit(0)
        content = f.read()
        root = xml.dom.minidom.parseString(content)
        result = {}
        for mumber in root.getElementsByTagName("package"):
            # 提取 location 的 href 属性值
            location = mumber.getElementsByTagName('location')[0]
            name = location.getAttribute('href')[9:]
            # 提取 checksum 的值
            checksum = mumber.getElementsByTagName('checksum')[0].firstChild.data
            result[name] = checksum
        f.close()
        os.remove(primaryfile)
        return result

    # 提供url，获取该url中官方repodata下的primary文件，将里面的{包名：sha256值}形成字典。
    def task(self, url):
        primaryfile = self._download_primaryfile(url)
        result = self._read_primaryfile(primaryfile)
        print("从primary文件识别到sha256：{}个".format(len(result.keys())))
        return result

